package com.zhouchao;

import com.zhouchao.dao.IUserMapper;
import com.zhouchao.persistence.io.Resources;
import com.zhouchao.persistence.session.SqlSession;
import com.zhouchao.persistence.session.SqlSessionFactory;
import com.zhouchao.persistence.session.SqlSessionFactoryBuilder;
import com.zhouchao.pojo.User;
import org.dom4j.DocumentException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;

/**
 * @Author: zhouchao
 * @Date: 2021/05/03 16:58
 * @Description:
 */
public class UserTest {
    private SqlSession session;

    @Test
    public void testSelect() throws Exception {
        User user = new User();
        user.setId(1);
        user.setUsername("zhangsan");
        IUserMapper userMapper = session.getMapper(IUserMapper.class);
        User resultUser = userMapper.findByCondition(user);
        System.out.println(resultUser);

        System.out.println("==========================");
        List<User> userList = userMapper.findAll();
        userList.forEach(System.out::println);
    }

    @Test
    public void testInsert()  {
        IUserMapper userMapper = session.getMapper(IUserMapper.class);
        User insertUser = new User();
        insertUser.setUsername("abc");
        System.out.println(userMapper.saveByEntity(insertUser));
    }

    @Test
    public void testUpdate() {
        IUserMapper userMapper = session.getMapper(IUserMapper.class);
        User updateUser = new User();
        updateUser.setId(6);
        updateUser.setUsername("xyz");
        System.out.println(userMapper.updateByEntity(updateUser));
    }

    @Test
    public void testDeleteByEntity() {
        IUserMapper userMapper = session.getMapper(IUserMapper.class);
        User deleteUser = new User();
        deleteUser.setId(6);
        System.out.println(userMapper.deleteByEntity(deleteUser));
    }


    @Test
    public void testDeleteByUserId() {
        IUserMapper userMapper = session.getMapper(IUserMapper.class);
        System.out.println(userMapper.deleteByUserId(4));
    }


    @Before
    public void init() throws PropertyVetoException, DocumentException {
        InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        session = sqlSessionFactory.openSession();
    }

}
